package com.yuanxin.chooseimage.imagechoosemodule;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.telecom.Call;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;

import com.bumptech.glide.Glide;
import com.yalantis.ucrop.UCrop;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yuanxin.chooseimage.R;
import com.yuanxin.chooseimage.camera.util.FileUtil;
import com.yuanxin.chooseimage.imagechoosemodule.adapter.FolderAdapter;
import com.yuanxin.chooseimage.imagechoosemodule.adapter.ImageGridAdapter;
import com.yuanxin.chooseimage.imagechoosemodule.bean.Folder;
import com.yuanxin.chooseimage.imagechoosemodule.bean.Image;
import com.yuanxin.chooseimage.imagechoosemodule.utils.FileUtils;
import com.yuanxin.chooseimage.imagechoosemodule.utils.ScreenUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.yuanxin.chooseimage.customutil.LocalUtil;
/**
 * 图片选择Fragment
 * Created by Nereo on 2015/4/7.
 */
public class MultiImageSelectorFragment extends Fragment {

    private final String TAG = "MultiImageSelectorFragment";

    private static final String KEY_TEMP_FILE = "key_temp_file";

    /**
     * 最大图片选择次数，int类型
     */
    public static final String EXTRA_SELECT_COUNT = "max_select_count";
    /**
     * 图片选择模式，int类型
     */
    public static final String EXTRA_SELECT_MODE = "select_count_mode";
    /**
     * 是否显示相机，boolean类型
     */
    public static final String EXTRA_SHOW_CAMERA = "show_camera";
    /**
     * 显示图片,视频
     */
    public static final String EXTRA_SHOW_PIC_VIDEO = "show_pic_video";
    /**
     * 图片剪切宽度
     */
    public static final String EXTRA_CUT_WIDTH = "cut_width";
    /**
     * 图片剪切高度
     */
    public static final String EXTRA_CUT_HEIGHT = "cut_height";
    /**
     * 默认选择的数据集
     */
    public static final String EXTRA_DEFAULT_IMAGE_SELECTED_LIST = "default_image_result";
    /**
     * 默认选择的数据集
     */
    public static final String EXTRA_DEFAULT_VIDEO_SELECTED_LIST = "default_video_result";
    /**
     * 单选
     */
    public static final int MODE_SINGLE = 0;
    /**
     * 多选
     */
    public static final int MODE_MULTI = 1;

    /**
     * 视频录制的时长
     */
    public static final String EXTRA_MAX_SECOND = "max_second";

    // 不同loader定义
    private static final int LOADER_ALL = 0;
    private static final int LOADER_CATEGORY = 1;
    // 请求加载系统照相机
    public static final int REQUEST_CAMERA = 100;


    // 结果数据
    private ArrayList<Image> resultImageList = new ArrayList<>();
    // 结果数据
    private ArrayList<String> resultVideoList = new ArrayList<>();
    // 文件夹数据
    private ArrayList<Folder> mResultFolder = new ArrayList<>();

    // 图片Grid
    private GridView mGridView;

    private ImageGridAdapter mImageAdapter;
    private FolderAdapter mFolderAdapter;

    private ListPopupWindow mFolderPopupWindow;

    // 类别
    private TextView mCategoryText;
    // 预览按钮
    private Button mPreviewBtn;
    // 底部View
    private View mPopupAnchorView;

    private int mDesireImageCount;

    private boolean hasFolderGened = false;
    private boolean mIsShowCamera = false;

    public static File mTmpFile;
    private int mIsShowPicVideo;

    private int cutWidth;
    private int cutHeight;

    private int maxSecond;

    private Handler handler;

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_multi_image, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 选择图片数量
        mDesireImageCount = getArguments().getInt(EXTRA_SELECT_COUNT);

        // 图片选择模式
        final int mode = getArguments().getInt(EXTRA_SELECT_MODE);

        resultImageList = (ArrayList<Image>) getArguments().getSerializable(EXTRA_DEFAULT_IMAGE_SELECTED_LIST);
        resultVideoList = getArguments().getStringArrayList(EXTRA_DEFAULT_VIDEO_SELECTED_LIST);


        // 是否显示照相机
        mIsShowCamera = getArguments().getBoolean(EXTRA_SHOW_CAMERA, true);
        //显示图片，视频
        mIsShowPicVideo = getArguments().getInt(EXTRA_SHOW_PIC_VIDEO, 0);
       // Log.e("MultiActivity", "mIsShowCamera-2--" + mIsShowCamera + "---mIsShowPicVideo-2--" + mIsShowPicVideo);
        mImageAdapter = new ImageGridAdapter(getActivity(), mIsShowCamera, 3);
        //
        cutHeight = getArguments().getInt(EXTRA_CUT_HEIGHT, 0);
        cutWidth = getArguments().getInt(EXTRA_CUT_WIDTH, 0);

        // 是否显示选择指示器
        mImageAdapter.showSelectIndicator(mode == MODE_MULTI);

        mPopupAnchorView = view.findViewById(R.id.footer);

        mCategoryText = (TextView) view.findViewById(R.id.category_btn);
        // 初始化，加载所有图片
        if (mIsShowPicVideo == 0) {
            mCategoryText.setText(R.string.folder_pic_all);
        } else {
            //获取拍摄时长
            maxSecond = getArguments().getInt(EXTRA_MAX_SECOND, 6);
            mCategoryText.setText(R.string.folder_video_all);
        }
        mCategoryText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mFolderPopupWindow == null) {
                    createPopupFolderList();
                }

                if (mFolderPopupWindow.isShowing()) {
                    mFolderPopupWindow.dismiss();
                } else {
                    mFolderPopupWindow.show();
                    int index = mFolderAdapter.getSelectIndex();
                    index = index == 0 ? index : index - 1;
                    mFolderPopupWindow.getListView().setSelection(index);
                }
            }
        });

        mPreviewBtn = (Button) view.findViewById(R.id.preview);
        // 初始化，按钮状态初始化
        if (resultImageList == null || resultImageList.size() <= 0) {
            mPreviewBtn.setText(R.string.preview);
            mPreviewBtn.setEnabled(false);
        }
        mPreviewBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO 预览
            }
        });

        mGridView = (GridView) view.findViewById(R.id.grid);
        mGridView.setAdapter(mImageAdapter);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mImageAdapter.isShowCamera()) {
                    // 如果显示照相机，则第一个Grid显示为照相机，处理特殊逻辑
                    if (i == 0) {
                        AndPermission.with(getActivity())
                                .permission(Permission.CAMERA)
                                .onGranted(new Action() {
                                    @Override
                                    public void onAction(List<String> permissions) {
                                        try {
                                            showCameraAction();
                                        } catch (Exception ex) {
                                            ex.printStackTrace();
                                        }
                                    }
                                })
                                .onDenied(new Action() {
                                    @Override
                                    public void onAction(List<String> permissions) {
                                        Toast.makeText(getContext(),"请前往设置给应用授权",Toast.LENGTH_SHORT).show();
                                        for (int i = 0; i < permissions.size(); i++) {
                                            // Log.e(TAG, "拒绝了权限：" + permissions.get(i));
                                        }
                                    }
                                }).start();

                    } else {
                        // 正常操作
                        Image image = (Image) adapterView.getAdapter().getItem(i);
                        selectImageFromGrid(image, mode);
                    }
                } else {
                    // 正常操作
                    Image image = (Image) adapterView.getAdapter().getItem(i);
                    selectImageFromGrid(image, mode);
                }
            }
        });
        mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_FLING) {
//                    Picasso.with(view.getContext()).pauseTag(TAG);
                    Glide.with(view.getContext());
                } else {
//                    Picasso.with(view.getContext()).resumeTag(TAG);
                    Glide.with(view.getContext());
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        mFolderAdapter = new FolderAdapter(getActivity(), mIsShowPicVideo);
    }

    /**
     * 创建弹出的ListView
     */
    private void createPopupFolderList() {
        Point point = ScreenUtils.getScreenSize(getActivity());
        int width = point.x;
        int height = (int) (point.y * (4.5f / 8.0f));
        mFolderPopupWindow = new ListPopupWindow(getActivity());
        mFolderPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        mFolderPopupWindow.setAdapter(mFolderAdapter);
        mFolderPopupWindow.setContentWidth(width);
        mFolderPopupWindow.setWidth(width);
        mFolderPopupWindow.setHeight(height);
        mFolderPopupWindow.setAnchorView(mPopupAnchorView);
        mFolderPopupWindow.setModal(true);
        mFolderPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                mFolderAdapter.setSelectIndex(i);

                final int index = i;
                final AdapterView v = adapterView;

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mFolderPopupWindow.dismiss();

                        if (index == 0) {
                            getActivity().getSupportLoaderManager().restartLoader(LOADER_ALL, null, mLoaderCallback);
                            if (mIsShowPicVideo == 0) {
                                mCategoryText.setText(R.string.folder_pic_all);
                            } else {
                                mCategoryText.setText(R.string.folder_video_all);
                            }
                            if (mIsShowCamera) {
                                mImageAdapter.setShowCamera(true);
                            } else {
                                mImageAdapter.setShowCamera(false);
                            }
                        } else {
                            Folder folder = (Folder) v.getAdapter().getItem(index);
                            if (null != folder) {
                                mImageAdapter.setData(folder.images);
                                mCategoryText.setText(folder.name);
                                // 设定默认选择
                                if (resultImageList != null && resultImageList.size() > 0) {
                                    mImageAdapter.setDefaultSelected(resultImageList);
                                }
                            }
                            mImageAdapter.setShowCamera(false);
                        }

                        // 滑动到最初始位置
                        mGridView.smoothScrollToPosition(0);
                    }
                }, 100);

            }
        });
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(KEY_TEMP_FILE, mTmpFile);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null) {
            mTmpFile = (File) savedInstanceState.getSerializable(KEY_TEMP_FILE);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 首次加载所有图片
        //new LoadImageTask().execute();
        getActivity().getSupportLoaderManager().initLoader(LOADER_ALL, null, mLoaderCallback);
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        // 相机拍照完成后，返回图片路径
//       // Log.i("MultiActivity", "onCameraShot-onActivityResult---" + mTmpFile);
//        if(requestCode == REQUEST_CAMERA){
//            if(resultCode == Activity.RESULT_OK) {
//                if (mTmpFile != null) {
//                    if (mCallback != null) {
//                        mCallback.onCameraShot(mTmpFile);
//                    }
//                }
//            }else{
//                while (mTmpFile != null && mTmpFile.exists()){
//                    boolean success = mTmpFile.delete();
//                    if(success){
//                        mTmpFile = null;
//                    }
//                }
//            }
//        }
//    }


    public void startCropImageIntent(String path) {
        Uri uri;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(new File(path));
        } else {
            uri = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".provider", new File(path));
        }
        int color = Color.parseColor("#21282C");//这个颜色和图片列表一致
        UCrop.Options options = new UCrop.Options();
        options.setCropFrameStrokeWidth(2);//裁剪框线的所需宽度（像素）
        options.setCropGridStrokeWidth(2);//网格线的所需宽度（像素）
        options.setActiveWidgetColor(color);//横向滑轮颜色
        options.setToolbarColor(color);//导航栏颜色
        options.setLogoColor(color);//logo颜色 注意，这个logo一闪而过
        options.setRootViewBackgroundColor(color);// 背景色
        options.setToolbarWidgetColor(Color.WHITE);//导航栏按钮色
        options.setStatusBarColor(color);//状态栏颜色
        options.withAspectRatio(1, 1);//宽高比
        options.withMaxResultSize(cutWidth == 0 ? 300 : cutWidth*2, cutHeight == 0 ? 300 : cutHeight*2);
        File file = null;
        try {
             file = FileUtils.createTmpFilePic(getActivity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        UCrop.of(uri, Uri.fromFile(file))
                .withOptions(options)
                .start(getActivity());
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (mFolderPopupWindow != null) {
            if (mFolderPopupWindow.isShowing()) {
                mFolderPopupWindow.dismiss();
            }
        }
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 选择相机
     */
    private void showCameraAction() {
        // 跳转到系统照相机
        Intent cameraIntent = null;
        if (mIsShowPicVideo == 0) {
            cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            try {
                mTmpFile = FileUtils.createTmpFilePic(getActivity());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            cameraIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            //允许记录的最长时间(以 秒 为单位)  例如：限制为60S
            cameraIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, maxSecond);
            //用于控制录制视频的质量；0——低质量；1——高质量
            cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            try {
                mTmpFile = FileUtils.createTmpFileVideo(getActivity());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            if (mTmpFile != null && mTmpFile.exists()) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
                } else {
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this.getContext(), this.getContext().getApplicationContext().getPackageName() + ".provider", mTmpFile));
                }
                //使用getActivity().startActivityForResult,activity才可以正常接收到REQUEST_CAMERA
                getActivity().startActivityForResult(cameraIntent, REQUEST_CAMERA);
            } else {
                Toast.makeText(getActivity(), "路径错误", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getActivity(), R.string.msg_no_camera, Toast.LENGTH_SHORT).show();
        }


    }

    /**
     * 选择图片操作
     *
     * @param image
     */
    private void selectImageFromGrid(Image image, int mode) {
        if (image != null) {
            // 多选模式
            if (mode == MODE_MULTI) {
                if (mIsShowPicVideo == 0) {//图片
                    boolean isExists = false;
                    int i = 0;
                    for (; i < resultImageList.size(); i++) {
                        if (resultImageList.get(i).filePath.equals(image.filePath)) {
                            isExists = true;
                            break;
                        }
                    }
                    if (isExists) {
                        resultImageList.remove(i);
                        if (resultImageList.size() != 0) {
                            mPreviewBtn.setEnabled(true);
                            mPreviewBtn.setText(getResources().getString(R.string.preview) + "(" + resultImageList.size() + ")");
                        } else {
                            mPreviewBtn.setEnabled(false);
                            mPreviewBtn.setText(R.string.preview);
                        }
                        updateDoneText(resultImageList.size());
                    } else {
                        // 判断选择数量问题
                        if (mDesireImageCount == resultImageList.size()) {
                            Toast.makeText(getActivity(), R.string.msg_amount_limit, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        mPreviewBtn.setEnabled(true);
                        mPreviewBtn.setText(getResources().getString(R.string.preview) + "(" + resultImageList.size() + ")");
                        resultImageList.add(image);
                        updateDoneText(resultImageList.size());
                    }
                } else {//视频
                    if (resultVideoList.contains(image.filePath)) {
                        resultVideoList.remove(image.filePath);
                        updateDoneText(resultVideoList.size());
                    } else {
                        // 判断选择数量问题
                        if (mDesireImageCount == resultVideoList.size()) {
                            Toast.makeText(getActivity(), R.string.msg_amount_limit, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        resultVideoList.add(image.filePath);
                        updateDoneText(resultVideoList.size());
                    }
                }
                mImageAdapter.select(image);
            } else if (mode == MODE_SINGLE) { //单选模式
                startCropImageIntent(image.filePath);
            }
        }
    }

    private void updateDoneText(int count) {
        Message m = handler.obtainMessage();
        m.what = 1;
        m.obj = String.format("%s(%d/%d)",
                getString(R.string.action_done), count, mDesireImageCount);
        m.arg1 = count;
        handler.sendMessage(m);
    }

    private LoaderManager.LoaderCallbacks<Cursor> mLoaderCallback = new LoaderManager.LoaderCallbacks<Cursor>() {

        private final String[] IMAGE_PROJECTION = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media.MIME_TYPE,
                MediaStore.Images.Media.SIZE,
                MediaStore.Images.Media._ID};

        private final String[] VIDEO_PROJECTION = {
                MediaStore.Video.Media.DATA,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.DATE_ADDED,
                MediaStore.Video.Media.MIME_TYPE,
                MediaStore.Video.Media.SIZE,
                MediaStore.Video.Media._ID};

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            CursorLoader cursorLoader = null;
            if (id == LOADER_ALL) {
                if (mIsShowPicVideo == 0) {
                    cursorLoader = new CursorLoader(getActivity(),
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                            IMAGE_PROJECTION[4] + ">0 AND " + IMAGE_PROJECTION[3] + "=? OR " + IMAGE_PROJECTION[3] + "=? ",
                            new String[]{"image/jpeg", "image/png"}, IMAGE_PROJECTION[2] + " DESC");
                } else {
                    cursorLoader = new CursorLoader(getActivity(),
                            MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION,
                            VIDEO_PROJECTION[4] + ">0 AND " + VIDEO_PROJECTION[3] + "=? OR " + VIDEO_PROJECTION[3] + "=? ",
                            new String[]{"video/mp4"}, VIDEO_PROJECTION[2] + " DESC");
                }
                return cursorLoader;
            } else if (id == LOADER_CATEGORY) {
                if (mIsShowPicVideo == 0) {
                    cursorLoader = new CursorLoader(getActivity(),
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION,
                            IMAGE_PROJECTION[4] + ">0 AND " + IMAGE_PROJECTION[0] + " like '%" + args.getString("path") + "%'",
                            null, IMAGE_PROJECTION[2] + " DESC");
                } else {
                    cursorLoader = new CursorLoader(getActivity(),
                            MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION,
                            VIDEO_PROJECTION[4] + ">0 AND " + VIDEO_PROJECTION[0] + " like '%" + args.getString("path") + "%'",
                            null, VIDEO_PROJECTION[2] + " DESC");
                }
                return cursorLoader;
            }

            return null;
        }

        private boolean fileExist(String path) {
            if (!TextUtils.isEmpty(path)) {
                return new File(path).exists();
            }
            return false;
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            String path = null;
            String name = null;
            long dateTime = 0;
            if (data != null) {
                if (data.getCount() > 0) {
                    List<Image> images = new ArrayList<>();
                    data.moveToFirst();
                    do {
                        if (mIsShowPicVideo == 0) {
                            path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                            name = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                            dateTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                        } else {
                            path = data.getString(data.getColumnIndexOrThrow(VIDEO_PROJECTION[0]));
                            name = data.getString(data.getColumnIndexOrThrow(VIDEO_PROJECTION[1]));
                            dateTime = data.getLong(data.getColumnIndexOrThrow(VIDEO_PROJECTION[2]));
                        }
                        Image image = null;
                        if (fileExist(path)) {
                            image = new Image(path, name, dateTime);
                            images.add(image);
                        }
                        if (!hasFolderGened) {
                            // 获取文件夹名称
                            File folderFile = new File(path).getParentFile();
                            if (folderFile != null && folderFile.exists()) {
                                String fp = folderFile.getAbsolutePath();
                                Folder f = getFolderByPath(fp);
                                if (f == null) {
                                    Folder folder = new Folder();
                                    folder.name = folderFile.getName();
                                    folder.path = fp;
                                    folder.cover = image;
                                    List<Image> imageList = new ArrayList<>();
                                    imageList.add(image);
                                    folder.images = imageList;
                                    mResultFolder.add(folder);
                                } else {
                                    f.images.add(image);
                                }
                            }
                        }

                    } while (data.moveToNext());

                    mImageAdapter.setData(images);
                    // 设定默认选择
                    if (resultImageList != null && resultImageList.size() > 0) {
                        mImageAdapter.setDefaultSelected(resultImageList);
                    }

                    if (!hasFolderGened) {
                        mFolderAdapter.setData(mResultFolder);
                        hasFolderGened = true;
                    }

                }
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    };

    private Folder getFolderByPath(String path) {
        if (mResultFolder != null) {
            for (Folder folder : mResultFolder) {
                if (TextUtils.equals(folder.path, path)) {
                    return folder;
                }
            }
        }
        return null;
    }


}
